import React, { Component } from 'react';
import { observer, inject } from "mobx-react";
import { message } from 'antd';
import styles from './index.module.less';
import SearchBar from '../common/searchBar';
import ListTab from '../common/listTab';
import ChatListItem from '../../components/ChatListItem';
import imSdk from '../../utils/imSdk';

@inject(({ chatState, projectState, taskState, commonState }) => ({ chatState, projectState, taskState, commonState }))
@observer
class ChatList extends Component {

    state = {
        activeGroupid: null,
        activeStatus: 0
    }

    componentWillMount() {
        document.addEventListener('chatListListener', this.chatListListener);
        const { chatgroupid } = this.props;
        // 其它页面跳转过来做的处理
        if (chatgroupid) {
            this.handleJumpToActiveItem(chatgroupid);
        }
    }

    componentWillReceiveProps(nextProps) {
        const { chatgroupid } = this.props;
        if (nextProps.chatgroupid && chatgroupid !== nextProps.chatgroupid) {
            this.handleJumpToActiveItem(nextProps.chatgroupid);
        }
    }

    componentDidUpdate() {
        // 列表跟新完成后，把当前activeItem滚动到列表顶部
        const nodeId = this.needScrollIntoViewNodeId;
        const viewNode = this[`node-${nodeId}`]
        if (nodeId && viewNode) {
            viewNode.scrollIntoView();
            this.needScrollIntoViewNodeId = false; // 屏蔽了每次渲染都会把activeItem滚动到列表顶部
        }
    }

    componentWillUnmount() {
        document.removeEventListener('chatListListener', this.chatListListener);
    }

    chatListListener = (event) => {
        const { activeStatus } = event.detail;
        this.setState({ activeStatus });
    }

    handleJumpToActiveItem = (chatgroupid) => {
        // console.log(chatgroupid);
        const { chatList = [] } = this.props.chatState;
        let pdata, gdata;
        try {
            chatList.forEach((v) => {
                v.groups.forEach((g) => {
                    if (g.groupid === chatgroupid) {
                        pdata = v;
                        gdata = g;
                        // 避免遍历太多，使用try catch捕捉错误的方式结束foreach循环
                        throw new Error('finded target');
                    }
                });
            })
        } catch (e) {
            console.log('--终止foreach循环遍历');
        }
        // console.log('----', chatgroupid, pdata, gdata);
        if (!gdata) {
            message.warn("暂无当前聊天");
            return;
        };
        this.viewDetail(pdata, gdata);
        // 用于滚动activeItem到列表顶部
        this.needScrollIntoViewNodeId = gdata.groupid;
    }

    viewDetail = (pdata, gdata) => {
        const { SessionItem } = gdata;
        const { setChatContent, chatId, getDetail } = this.props.chatState;
        if (!SessionItem || !SessionItem.SessionId) {
            message.warn("暂无当前聊天");
            return;
        }
        const { SessionId, SessionType } = SessionItem;

        if (chatId === SessionId) return;

        this.setState({ activeGroupid: gdata.groupid });
        getDetail({ ...pdata, group: gdata });
        setChatContent(SessionId, []);
        imSdk.createChatInstance(SessionType, SessionId);

        // 切换聊天组的时候默认展开侧边栏
        this.props.commonState.setStateValue('sideOpen', true);
        if (pdata.projectid) {
            this.props.projectState.getDetail(pdata); // 获取项目详情 
        } else if (gdata.objectid) {
            this.props.taskState.getDetail({ taskid: gdata.objectid }); // // 获取任务详情 
        }
    }

    renderItem(items, chatDraftCache, chatId) {
        const { activeGroupid } = this.state;
        return (
            items.map((v, i) => (
                <ChatListItem
                    innerRef={(d, id) => this[`node-${id}`] = d}
                    key={`chatItem${i}`}
                    data={v}
                    activeGroupid={activeGroupid}
                    onClick={this.viewDetail}
                    chatId={chatId}
                    chatDraftCache={chatDraftCache}
                />
            ))
        )
    }

    onChange = (activeStatus) => () => {
        this.setState({ activeStatus });
    }

    render() {
        const { chatList0, chatList1, chatDraftCache, chatId, totalMsgCount1 } = this.props.chatState;
        const { activeStatus } = this.state;
        const chatList = activeStatus ? chatList1 : chatList0;
        return (
            <>
                <SearchBar stateKey={'chatState'} add />
                <ListTab onChange={this.onChange} activeStatus={activeStatus} totalMsgCount1={totalMsgCount1} />
                <div className={styles.listContent}>
                    {this.renderItem(chatList, chatDraftCache, chatId)}
                </div>
            </>
        );
    }
}

export default ChatList